package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"user/models"
)

type UserController struct {
	beego.Controller
}

type JsonR struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *UserController) Add() {
	name := c.GetString("name")
	age, _ := c.GetInt("age")
	tel := c.GetString("tel")
	area := c.GetString("area")
	grade := c.GetString("grade")
	status := c.GetString("status")
	user := models.User{
		Name:   name,
		Age:    age,
		Tel:    tel,
		Area:   area,
		Grade:  grade,
		Status: status,
	}
	err := models.DB.Create(&user).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "添加成功",
			Data: user,
		}
		c.ServeJSON()
	}
}

func (c *UserController) List() {
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 5)
	var count int64
	models.DB.Model(&models.User{}).Count(&count)
	offset := (page - 1) * size
	var goods []models.User
	err := models.DB.Model(&models.User{}).Offset(offset).Limit(size).Find(&goods).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "查询失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		pageDate := make(map[string]interface{})
		pageDate["count"] = count
		pageDate["goods"] = goods
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "查询成功",
			Data: goods,
		}
		c.ServeJSON()
	}
}

func (c *UserController) Del() {
	id, _ := c.GetInt("id")
	err := models.DB.Where("Id=?", id).Delete(&models.User{}).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "删除失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
